<template>
  <div class="container">
    <!-- 添加页面导航 -->
    <PageNavigation pageTitle="房源管理" />
    
    <div class="page-header">
      <h2>房源管理</h2>
      <p>管理系统内的所有房源信息，审核用户上传的房源 (house_info 表)</p>
    </div>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="queryParams" class="search-form">
      <el-form-item label="房源标题">
        <el-input v-model="queryParams.title" placeholder="请输入房源标题" clearable style="width: 220px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="房源状态" clearable style="width: 120px">
          <el-option label="全部" value=""></el-option>
          <el-option label="待审核" value="0"></el-option>
          <el-option label="在售" value="1"></el-option>
          <el-option label="已售" value="2"></el-option>
          <el-option label="下架" value="3"></el-option>
          <el-option label="审核未通过" value="4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery" :loading="loading" icon="Search">搜索</el-button>
        <el-button @click="resetQuery" icon="Refresh">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="houseList" style="width: 100%" v-loading="loading" border stripe>
      <el-table-column type="index" width="50" />
      <el-table-column prop="title" label="房源标题">
        <template #default="scope">
          <span style="color: #409EFF; font-weight: bold;">{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" width="120" />
      <el-table-column prop="area" label="面积" width="100">
        <template #default="scope">
          {{ scope.row.area }}㎡
        </template>
      </el-table-column>
      <el-table-column prop="address" label="地址">
        <template #default="scope">
          {{ scope.row.district || '' }}{{ scope.row.address || '' }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center" width="170">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.status === '0'" type="warning">待审核</el-tag>
          <el-tag v-else-if="scope.row.status === '1'" type="success">在售</el-tag>
          <el-tag v-else-if="scope.row.status === '2'" type="info">已售</el-tag>
          <el-tag v-else-if="scope.row.status === '3'" type="danger">下架</el-tag>
          <el-tag v-else-if="scope.row.status === '4'" type="danger">审核未通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="320" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleView(scope.row)">查看</el-button>
          <el-button size="small" @click="handleEdit(scope.row)" :disabled="scope.row.status === '2'">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          
          <!-- 基于不同状态显示不同操作按钮 -->
          <template v-if="scope.row.status === '0'">
            <el-button size="small" type="success" @click="handleApprove(scope.row)">审核</el-button>
          </template>
          
          <template v-if="scope.row.status === '1'">
            <el-button size="small" type="warning" @click="handleStatusChange(scope.row, '3')">下架</el-button>
            <el-button size="small" type="info" @click="handleStatusChange(scope.row, '2')">已售</el-button>
          </template>
          
          <template v-if="scope.row.status === '3'">
            <el-button size="small" type="success" @click="handleStatusChange(scope.row, '1')">上架</el-button>
          </template>
          
          <template v-if="scope.row.status === '4'">
            <el-button size="small" type="success" @click="handleApprove(scope.row)">重新审核</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="queryParams.pageSize"
        :current-page="queryParams.pageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 审核对话框 -->
    <el-dialog title="房源审核" v-model="approveDialogVisible" width="500px">
      <el-form ref="approveFormRef" :model="approveForm" label-width="100px">
        <el-form-item label="房源标题">
          <span>{{ currentHouse.title }}</span>
        </el-form-item>
        <el-form-item label="房源信息">
          <div class="house-info">
            <p><strong>价格:</strong> {{ currentHouse.price }}</p>
            <p><strong>面积:</strong> {{ currentHouse.area }}</p>
            <p><strong>地址:</strong> {{ currentHouse.address }}</p>
            <p><strong>创建时间:</strong> {{ formatDateTime(currentHouse.createTime) }}</p>
          </div>
        </el-form-item>
        <el-form-item label="审核结果" prop="approveStatus">
          <el-radio-group v-model="approveForm.approveStatus">
            <el-radio label="1">通过</el-radio>
            <el-radio label="4">不通过</el-radio>
          </el-radio-group>
          <div class="form-tip">
            <small>注意：审核通过后房源状态将变为"在售"</small>
          </div>
        </el-form-item>
        <el-form-item label="审核备注" prop="remark" v-if="approveForm.approveStatus === '4'">
          <el-input v-model="approveForm.remark" type="textarea" :rows="3" placeholder="请输入不通过的原因（必填）" required></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="approveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitApprove">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 查看详情对话框 -->
    <el-dialog title="房源详情" v-model="viewDialogVisible" width="650px">
      <div v-loading="loading" class="house-detail" v-if="currentHouse.id || currentHouse.houseId">
        <h3>{{ currentHouse.title }}</h3>
        <div class="house-detail-info">
          <div class="house-detail-row">
            <span class="label">价格:</span>
            <span class="value">{{ currentHouse.price }}{{ currentHouse.priceUnit || '万' }}</span>
          </div>
          <div class="house-detail-row">
            <span class="label">面积:</span>
            <span class="value">{{ currentHouse.area }}㎡</span>
          </div>
          <div class="house-detail-row">
            <span class="label">房源类型:</span>
            <span class="value">
              {{ 
                currentHouse.houseType === '1' ? '住宅' : 
                currentHouse.houseType === '2' ? '公寓' : 
                currentHouse.houseType === '3' ? '别墅' : 
                currentHouse.houseType === '4' ? '商铺' : 
                currentHouse.houseType === '5' ? '写字楼' : '未知' 
              }}
            </span>
          </div>
          <div class="house-detail-row">
            <span class="label">户型:</span>
            <span class="value">
              {{ currentHouse.bedroom || 0 }}室{{ currentHouse.livingRoom || 0 }}厅{{ currentHouse.bathroom || 0 }}卫
            </span>
          </div>
          <div class="house-detail-row">
            <span class="label">装修:</span>
            <span class="value">
              {{ 
                currentHouse.decoration === '1' ? '毛坯' : 
                currentHouse.decoration === '2' ? '简装' : 
                currentHouse.decoration === '3' ? '精装' : 
                currentHouse.decoration === '4' ? '豪装' : '未知' 
              }}
            </span>
          </div>
          <div class="house-detail-row">
            <span class="label">楼层:</span>
            <span class="value">{{ currentHouse.floor || '-' }}/{{ currentHouse.totalFloor || '-' }}层</span>
          </div>
          <div class="house-detail-row">
            <span class="label">朝向:</span>
            <span class="value">{{ currentHouse.orientation || '未知' }}</span>
          </div>
          <div class="house-detail-row">
            <span class="label">地址:</span>
            <span class="value">
              {{ currentHouse.province || '' }}{{ currentHouse.city || '' }}{{ currentHouse.district || '' }}{{ currentHouse.address || '' }}
            </span>
          </div>
          <div class="house-detail-row">
            <span class="label">状态:</span>
            <span class="value">
              <el-tag v-if="currentHouse.status === '0'" type="warning">待审核</el-tag>
              <el-tag v-else-if="currentHouse.status === '1'" type="success">在售</el-tag>
              <el-tag v-else-if="currentHouse.status === '2'" type="info">已售</el-tag>
              <el-tag v-else-if="currentHouse.status === '3'" type="danger">下架</el-tag>
              <el-tag v-else-if="currentHouse.status === '4'" type="danger">审核未通过</el-tag>
            </span>
          </div>
          <div class="house-detail-row">
            <span class="label">创建时间:</span>
            <span class="value">{{ formatDateTime(currentHouse.createTime) }}</span>
          </div>
          <div class="house-detail-row" v-if="currentHouse.auditRemark">
            <span class="label">审核备注:</span>
            <span class="value">{{ currentHouse.auditRemark }}</span>
          </div>
          <div class="house-detail-row">
            <span class="label">描述:</span>
            <span class="value">{{ currentHouse.description || '暂无描述' }}</span>
          </div>
        </div>
        
        <!-- 房源图片 -->
        <div class="house-images" v-if="currentHouse.images && currentHouse.images.length > 0">
          <h4>房源图片</h4>
          <el-carousel :interval="4000" type="card" height="200px">
            <el-carousel-item v-for="(image, index) in currentHouse.images" :key="index">
              <img 
                :src="getHouseImageUrl(image)" 
                :alt="currentHouse.title" 
                @error="onImageError" 
              />
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
      <div v-else class="empty-data">
        <el-empty description="暂无房源详情"></el-empty>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
          <el-button 
            v-if="currentHouse.status === '0'" 
            type="success" 
            @click="handleApproveFromDetail">审核</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 编辑房源对话框 -->
    <el-dialog title="编辑房源" v-model="editDialogVisible" width="650px">
      <el-form :model="houseForm" :rules="houseRules" ref="houseFormRef" label-width="100px">
        <el-form-item label="房源标题" prop="title">
          <el-input v-model="houseForm.title" placeholder="请输入房源标题"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="houseForm.price" placeholder="例如: 300万"></el-input>
        </el-form-item>
        <el-form-item label="面积" prop="area">
          <el-input v-model="houseForm.area" placeholder="例如: 120㎡"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="houseForm.address" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="houseForm.description" :rows="4" placeholder="请输入房源描述"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHouseForm">更新</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageNavigation from '@/components/common/PageNavigation.vue'
import { fetchHouseList as fetchHouseListAPI, getHouseDetail, auditHouse, changeHouseStatus, updateHouse, deleteHouse } from '@/api/admin/house'
import { getFullImageUrl } from '@/utils/imageUrl'

const route = useRoute()

// 查询参数
const queryParams = reactive({
  title: '',
  status: '',
  pageNum: 1,
  pageSize: 10
})

const houseList = ref([])
const total = ref(0)
const loading = ref(false)

// 审核相关
const approveDialogVisible = ref(false)
const approveForm = reactive({
  houseId: '',
  approveStatus: '1', // 默认通过
  remark: ''
})
const currentHouse = ref({})

// 查看详情对话框
const viewDialogVisible = ref(false)

// 编辑对话框
const editDialogVisible = ref(false)
const houseFormRef = ref(null)
const houseForm = reactive({
  id: '',
  title: '',
  price: '',
  area: '',
  address: '',
  description: '',
  status: ''
})

// 房源表单验证规则
const houseRules = {
  title: [
    { required: true, message: '请输入房源标题', trigger: 'blur' },
    { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入面积', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ]
}

// 区域选项（可以从后端获取或固定值）
const districtOptions = ref(['朝阳区', '海淀区', '东城区', '西城区', '丰台区', '石景山区', '通州区', '昌平区'])

// 日期格式化函数
const formatDateTime = (timestamp) => {
  if (!timestamp) return '暂无数据'
  
  const date = new Date(timestamp)
  
  // 格式化为中国时间 (GMT+8)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 监听路由参数变化
watch(
  () => route.query,
  (query) => {
    if (query.houseId) {
      const houseId = parseInt(query.houseId)
      // 查找对应的房源
      const house = houseList.value.find(h => h.id === houseId)
      if (house && house.status === '0') {
        // 自动打开审核对话框
        handleApprove(house)
      } else if (!house) {
        // 如果在当前页面没找到，可能需要搜索
        queryParams.title = ''
        queryParams.status = '0'
        loadHouseList().then(() => {
          // 再次尝试查找房源
          setTimeout(() => {
            const foundHouse = houseList.value.find(h => h.id === houseId)
            if (foundHouse && foundHouse.status === '0') {
              handleApprove(foundHouse)
            } else {
              ElMessage.warning(`未找到ID为${houseId}的待审核房源`)
            }
          }, 600)
        })
      }
    }
  },
  { immediate: true }
)

// 初始化页面
onMounted(() => {
  loadHouseList()
})

// 获取房源列表
const loadHouseList = async () => {
  loading.value = true
  try {
    console.log('搜索参数:', queryParams)
    const res = await fetchHouseListAPI({
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      title: queryParams.title,
      status: queryParams.status
    })
    
    if (res.code === 200) {
      houseList.value = res.data.records || []
      total.value = res.data.total || 0
      console.log('获取到数据:', houseList.value)
      
      // 添加搜索结果反馈
      if (queryParams.title || queryParams.status) {
        if (houseList.value.length === 0) {
          ElMessage({
            message: '未找到符合条件的房源',
            type: 'warning'
          })
        } else {
          ElMessage({
            message: `找到 ${total.value} 条符合条件的记录`,
            type: 'success',
            duration: 2000
          })
        }
      }
    } else {
      ElMessage.error(res.msg || '获取房源列表失败')
    }
  } catch (error) {
    console.error('获取房源列表失败:', error)
    ElMessage.error('获取房源列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  console.log('执行搜索操作，参数:', queryParams)
  queryParams.pageNum = 1
  ElMessage({
    message: '正在搜索...',
    type: 'info',
    duration: 1000
  })
  setTimeout(() => {
    loadHouseList()
  }, 300)
}

// 重置
const resetQuery = () => {
  queryParams.title = ''
  queryParams.status = ''
  ElMessage({
    message: '已重置搜索条件',
    type: 'success',
    duration: 1000
  })
  setTimeout(() => {
    handleQuery()
  }, 300)
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  loadHouseList()
}

// 分页页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  loadHouseList()
}

// 查看房源详情
const handleView = async (row) => {
  loading.value = true
  try {
    // 先加载基本信息
    currentHouse.value = { ...row }
    
    // 确保使用正确的ID字段
    const houseId = row.houseId || row.id
    
    // 通过API获取完整的房源详情
    const res = await getHouseDetail(houseId)
    if (res.code === 200 && res.data) {
      // 使用API返回的详细数据更新当前房源信息
      currentHouse.value = {
        ...currentHouse.value,
        ...res.data,
        // 确保ID字段映射正确
        id: res.data.houseId || res.data.id,
        houseId: res.data.houseId || res.data.id,
        // 状态文本映射
        statusText: getStatusText(res.data.status),
        // 处理图片数组，确保正确格式
        images: Array.isArray(res.data.images) ? res.data.images : []
      }
      console.log('房源详情数据:', currentHouse.value)
    } else {
      ElMessage.warning('获取房源详情失败')
    }
  } catch (error) {
    console.error('获取房源详情错误:', error)
    ElMessage.error('获取房源详情失败')
  } finally {
    loading.value = false
    viewDialogVisible.value = true
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    '0': '待审核',
    '1': '在售',
    '2': '已售',
    '3': '已下架',
    '4': '审核未通过'
  }
  return statusMap[status] || '未知状态'
}

// 从详情页面打开审核
const handleApproveFromDetail = () => {
  // 检查房源状态是否为待审核(0)
  if (currentHouse.value.status !== '0') {
    ElMessage.error('只能审核待审核状态的房源')
    return
  }
  
  // 关闭详情对话框
  viewDialogVisible.value = false
  
  // 直接调用handleApprove函数，复用逻辑
  handleApprove(currentHouse.value)
}

// 编辑房源
const handleEdit = async (row) => {
  try {
    loading.value = true;
    // 确保获取到正确的ID
    const houseId = row.houseId || row.id;
    
    // 检查ID是否存在
    if (!houseId) {
      console.error("无法获取有效的房源ID:", row);
      ElMessage.error("无法获取有效的房源ID");
      loading.value = false;
      return;
    }
    
    console.log("开始编辑房源, ID:", houseId);

    // 先获取完整的房源详情
    const res = await getHouseDetail(houseId);
    
    if (res.code === 200 && res.data) {
      const houseData = res.data;
      console.log("获取到房源详情:", houseData);
      
      // 正确填充表单数据
      houseForm.id = houseData.houseId || houseData.id; // 确保有ID
      houseForm.title = houseData.title || '';
      houseForm.price = houseData.price || '';
      houseForm.area = houseData.area || '';
      houseForm.address = houseData.address || '';
      houseForm.description = houseData.description || '';
      houseForm.status = houseData.status || '';
      
      console.log("已填充表单:", houseForm);
    } else {
      console.error("获取房源详情失败, 使用行数据填充");
      Object.assign(houseForm, { 
        id: houseId, // 使用之前获取的ID
        title: row.title,
        price: row.price,
        area: row.area,
        address: row.address,
        description: row.description || '',
        status: row.status
      });
    }
  } catch (error) {
    console.error("编辑房源时出错:", error);
    ElMessage.error("获取房源详情失败");
    
    // 失败时仍使用行数据
    const houseId = row.houseId || row.id;
    Object.assign(houseForm, { 
      id: houseId, // 使用之前获取的ID
      title: row.title,
      price: row.price,
      area: row.area,
      address: row.address,
      description: row.description || '',
      status: row.status
    });
  } finally {
    loading.value = false;
    editDialogVisible.value = true;
  }
}

// 删除房源
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除房源 "${row.title}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      const res = await deleteHouse(row.id)
      
      if (res.code === 200) {
        ElMessage.success('删除成功')
        loadHouseList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 取消删除
  })
}

// 打开审核对话框
const handleApprove = async (row) => {
  // 检查房源状态是否为待审核(0)
  if (row.status !== '0') {
    ElMessage.error('只能审核待审核状态的房源')
    return
  }

  try {
    // 确保房源ID有效
    const houseId = row.houseId || row.id
    if (!houseId) {
      console.error('房源ID无效:', row)
      ElMessage.error('无法获取有效的房源ID')
      return
    }
    
    console.log('审核房源信息:', row)
    console.log('房源ID类型:', typeof houseId, '值:', houseId)
    
    // 先设置当前房源信息，防止API调用失败时没有数据显示
    currentHouse.value = row
    approveForm.houseId = houseId
    approveForm.approveStatus = '1'  // 默认通过
    approveForm.remark = ''
    
    // 在打开审核对话框前，尝试从后端获取最新的房源状态
    loading.value = true
    console.log('正在获取房源ID:', houseId, '的最新状态')

    getHouseDetail(houseId)
      .then(res => {
        if (res.code === 200 && res.data) {
          console.log('获取房源状态成功:', res.data)
          // 再次检查房源状态
          if (res.data.status !== '0') {
            ElMessage.error('该房源当前状态不是待审核状态，可能已被其他管理员处理')
            return
          }
          
          // 更新房源信息
          currentHouse.value = res.data
          // 再次确保ID字段正确设置
          approveForm.houseId = res.data.houseId || res.data.id || houseId
          console.log('最终使用的房源ID:', approveForm.houseId)
        } else {
          console.warn('获取房源状态接口返回非成功状态:', res)
          ElMessage.warning('获取最新房源状态失败，使用当前页面数据')
        }
      })
      .catch(error => {
        console.error('获取房源状态请求失败:', error)
        ElMessage.warning('获取最新状态失败，使用当前页面数据继续')
      })
      .finally(() => {
        // 无论如何都显示对话框，确保用户可以继续操作
        approveDialogVisible.value = true
        loading.value = false
      })
  } catch (error) {
    console.error('处理审核对话框时出错:', error)
    ElMessage.error('处理审核对话框时出错')
    
    // 出错后也显示对话框，避免界面卡死
    approveDialogVisible.value = true
    loading.value = false
  }
}

// 提交审核
const submitApprove = async () => {
  // 验证审核不通过时必须填写原因
  if (approveForm.approveStatus === '4' && !approveForm.remark) {
    ElMessage.warning('请填写审核不通过的原因')
    return
  }
  
  try {
    loading.value = true
    // 打印当前表单数据，用于调试
    console.log('提交审核表单数据:', approveForm)
    
    // 确保使用正确的房源ID
    const houseId = approveForm.houseId || currentHouse.value.id || currentHouse.value.houseId
    
    const data = {
      houseId: parseInt(houseId), // 确保ID是数字类型
      status: approveForm.approveStatus,
      remark: approveForm.remark
    }
    
    // 确保houseId有值
    if (!data.houseId) {
      ElMessage.error('房源ID不能为空')
      console.error('审核提交时房源ID为空:', approveForm, currentHouse.value)
      return
    }
    
    console.log('提交到后端的数据:', data)
    
    const res = await auditHouse(data)
    if (res.code === 200) {
      ElMessage.success(`房源 "${currentHouse.value.title}" 审核${approveForm.approveStatus === '1' ? '通过' : '不通过'}`)
      approveDialogVisible.value = false
      
      // 刷新列表
      loadHouseList()
    } else {
      // 详细处理后端返回的错误信息
      if (res.msg && res.msg.includes('状态不正确')) {
        ElMessage.error('审核失败：房源状态已变更，请刷新页面后重试')
        // 关闭对话框并刷新列表，以获取最新状态
        approveDialogVisible.value = false
        loadHouseList()
      } else {
        ElMessage.error(res.msg || '审核失败')
      }
    }
  } catch (error) {
    console.error('审核失败:', error)
    
    // 针对特定错误类型提供更具体的提示
    if (error.response && error.response.data && error.response.data.msg) {
      ElMessage.error(`审核失败: ${error.response.data.msg}`)
    } else {
      ElMessage.error('审核失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 修改房源状态
const handleStatusChange = async (row, status) => {
  // 确保获取到正确的ID
  const houseId = row.houseId || row.id;
  
  // 检查ID是否存在
  if (!houseId) {
    console.error("无法获取有效的房源ID:", row);
    ElMessage.error("无法获取有效的房源ID");
    return;
  }
  
  const statusText = {
    '1': '上架',
    '2': '标记为已售',
    '3': '下架'
  }
  
  ElMessageBox.confirm(`确定要将房源 "${row.title}" ${statusText[status]}吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      console.log('修改房源状态, ID:', houseId, '新状态:', status)
      const res = await changeHouseStatus({
        houseId: houseId,
        status: status
      })
      
      if (res.code === 200) {
        ElMessage.success(`房源${statusText[status]}成功`)
        loadHouseList()
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
    } catch (error) {
      console.error('修改状态失败:', error)
      ElMessage.error('修改状态失败，请稍后重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 取消操作
  })
}

// 提交房源表单
const submitHouseForm = async () => {
  if (!houseFormRef.value) return
  
  try {
    await houseFormRef.value.validate()
    
    loading.value = true
    console.log('提交房源编辑表单')
    
    // 检查ID是否存在
    if (!houseForm.id) {
      ElMessage.error('房源ID不能为空')
      console.error('提交表单时房源ID为空:', houseForm)
      loading.value = false
      return
    }
    
    try {
      // 先尝试获取完整的房源数据，确保我们不会丢失字段
      const detailRes = await getHouseDetail(houseForm.id)
      if (detailRes.code === 200 && detailRes.data) {
        const originalHouse = detailRes.data
        console.log('获取到原始房源数据:', originalHouse)
        
        // 构建提交数据 - 保留原有数据，只更新修改的字段
        const formData = {
          ...originalHouse,  // 保留所有原始字段
          
          // 更新编辑的字段
          title: houseForm.title,
          price: houseForm.price,
          area: houseForm.area,
          address: houseForm.address,
          description: houseForm.description,
          
          // 确保ID字段正确 - 后端权限验证需要houseId字段
          id: originalHouse.id,  // 可能在后端使用
          houseId: originalHouse.houseId || originalHouse.id,
          
          // 发布者和经纪人ID是权限验证的关键
          publisherId: originalHouse.publisherId,
          agentId: originalHouse.agentId || 
                  (originalHouse.agent && (originalHouse.agent.id || originalHouse.agent.agentId)) || 
                  originalHouse.agent_id,
        }
        
        console.log('提交房源修改，关键字段:',  
                    '房源ID:', formData.houseId || formData.id,
                    '发布者ID:', formData.publisherId, 
                    '经纪人ID:', formData.agentId)
        
        try {
          // 使用管理员专用更新函数代替普通更新
          const res = await updateHouse(formData)
          
          if (res.code === 200) {
            ElMessage.success('房源信息更新成功')
            editDialogVisible.value = false
            // 重新加载列表并立即尝试验证更新结果
            await loadHouseList()
            
            // 检查更新后的数据
            setTimeout(async () => {
              try {
                const verifyRes = await getHouseDetail(formData.houseId || formData.id)
                if (verifyRes.code === 200 && verifyRes.data) {
                  console.log('更新后的房源数据:', verifyRes.data);
                  // 验证是否更新成功
                  if (verifyRes.data.title === formData.title) {
                    console.log('数据验证成功: 标题已更新');
                  } else {
                    console.warn('数据验证失败: 标题未更新', {
                      expected: formData.title,
                      actual: verifyRes.data.title
                    });
                  }
                }
              } catch (e) {
                console.error('验证更新结果时出错:', e);
              }
            }, 1000);
          } else {
            ElMessage.error(res.msg || '更新失败')
          }
        } catch (apiError) {
          console.error('API调用失败:', apiError)
          
          // 检查是否为权限错误
          if (apiError.message && apiError.message.includes('无权')) {
            ElMessage({
              type: 'warning',
              message: '权限验证失败，尝试使用备用方案...',
              duration: 3000
            });
            
            // 备用方案: 再次尝试使用普通更新函数
            try {
              const fallbackRes = await updateHouse(formData)
              
              if (fallbackRes.code === 200) {
                ElMessage.success('房源信息已使用备用方案更新成功');
                editDialogVisible.value = false;
                loadHouseList();
              } else {
                ElMessage.error('备用更新方案也失败，请联系系统管理员');
              }
            } catch (fallbackError) {
              ElMessage.error('所有更新尝试均已失败，请联系系统管理员');
            }
          } else {
            ElMessage.error(`更新失败: ${apiError.message || '系统错误'}`)
          }
        }
      } else {
        ElMessage.error('获取房源详情失败，无法更新')
      }
    } catch (detailError) {
      console.error('获取房源详情失败:', detailError)
      ElMessage.error('无法获取完整房源信息，更新失败')
    }
  } catch (error) {
    console.error('提交房源编辑表单失败:', error)
    ElMessage.error('提交失败: ' + (error.message || '请稍后重试'))
  } finally {
    loading.value = false
  }
}

// 图片加载错误处理
const onImageError = (e) => {
  const originalSrc = e.target.getAttribute('data-original-src') || e.target.src;
  console.error('图片加载失败', originalSrc);
  
  // 保存原始路径用于调试
  e.target.setAttribute('data-original-src', originalSrc);
  
  // 设置默认图片，确保路径正确
  e.target.src = '/images/house/default-house.jpg';
  
  // 防止循环触发error事件
  e.target.onerror = null;
}

// 获取房源图片URL
const getHouseImageUrl = (image) => {
  if (!image) return '/images/house/default-house.jpg';
  
  // 如果是字符串，直接处理
  if (typeof image === 'string') {
    return getFullImageUrl(image);
  }
  
  // 如果是对象，尝试提取图片URL
  if (typeof image === 'object') {
    // 适配多种可能的字段名
    const imageUrl = image.imageUrl || image.image_url || image.url || '';
    return getFullImageUrl(imageUrl);
  }
  
  return '/images/house/default-house.jpg';
}
</script>

<style scoped>
.container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  margin: 0 0 10px 0;
}

.page-header p {
  color: #666;
  margin: 0;
}

.search-form {
  margin-bottom: 20px;
  background: #f9f9f9;
  padding: 20px;
  border-radius: 4px;
}

.separator {
  margin: 0 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 房源详情样式 */
.house-detail h3 {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 20px;
}

.house-detail-info {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.house-detail-row {
  display: flex;
  margin-bottom: 10px;
}

.house-detail-row .label {
  width: 100px;
  font-weight: bold;
}

.house-images img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 审核对话框中的房源信息 */
.house-info {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
}

.house-info p {
  margin: 5px 0;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

/* 空数据样式 */
.empty-data {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}
</style> 